package com.infisight.hudprojector.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.animation.AnimationUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.infisight.hudprojector.R;
import com.infisight.hudprojector.data.DataMusicClass;
import com.infisight.hudprojector.fragment.MusicFragment;
import com.infisight.hudprojector.fragment.MusicPlayFragment;
import com.infisight.hudprojector.util.LrcProcess;
import com.infisight.hudprojector.util.LrcProcess.LrcContent;
import com.infisight.hudprojector.util.LrcView;
import com.infisight.hudprojector.util.MusicList;

/**
 * 项目名称 : FRMusic
 * 
 * @author 作者 : fengrui
 * @date 创建时间：2015年8月7日 下午4:04:32
 * @version 1.0
 */
public class MusicService extends Service implements Runnable {

	private MediaPlayer mediaPlayer;
	private List<DataMusicClass> lists;
	// 当前播放位置
	public static int mid = 0;
	public static Boolean isRun = true;
	public LrcProcess lrcProcess;
	public LrcView lrcView;
	public static int playing_id;
	public static Boolean playing = false;
	SharedPreferences sp;
	Gson gson = null;

	@Override
	public void onCreate() {
		lists = MusicList.getMusicData(getApplicationContext());
		SeekBarBroadcastReceiver receiver = new SeekBarBroadcastReceiver();
		IntentFilter filter = new IntentFilter("com.example.frmusic.seekBar");
		this.registerReceiver(receiver, filter);
		new Thread(this).start();
		sp = getApplicationContext().getSharedPreferences("bg_music_info", 0);
		super.onCreate();
	}

	// 进度条状态的广播接收
	private class SeekBarBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			int seekBarPosition = intent.getIntExtra("seekBarPosition", 0);
			mediaPlayer.seekTo(seekBarPosition * mediaPlayer.getDuration()
					/ 100);
			mediaPlayer.start();
		}

	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		gson = new Gson();
		Log.i("TAG", "onStart");
		if (intent != null) {
			String play = intent.getStringExtra("play");
			mid = intent.getIntExtra("id", 0);
			if (intent.getStringExtra("listType") != null) {
				lists = gson.fromJson(intent.getStringExtra("listType"),
						new TypeToken<List<DataMusicClass>>() {
						}.getType());
			}
			if (play != null) {
				if (play.equals("play")) {
					if (null != mediaPlayer) {
						mediaPlayer.release();
						mediaPlayer = null;
					}
					playMusic(mid);
				} else if (play.equals("pause")) {
					if (null != mediaPlayer) {
						mediaPlayer.pause();
					}
				} else if (play.equals("playing")) {
					if (null != mediaPlayer) {
						mediaPlayer.start();
					} else {
						playMusic(mid);
					}
				} else if (play.equals("replaying")) {

				} else if (play.equals("next")) {
					int id = intent.getIntExtra("id", 0);
					playMusic(id);
				} else if (play.equals("last")) {
					int id = intent.getIntExtra("id", 0);
					playMusic(id);
				}
			}
		}
		super.onStart(intent, startId);
	}

	@Override
	public void run() {
		while (isRun) {
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (null != mediaPlayer) {
				try {
					int position = mediaPlayer.getCurrentPosition();
					int total = mediaPlayer.getDuration();
					Intent intent = new Intent("com.example.frmusic.progress");
					intent.putExtra("position", position);
					intent.putExtra("total", total);
					sendBroadcast(intent);
					if (mediaPlayer.isPlaying()) {
						playing = true;
					} else {
						playing = false;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					mediaPlayer = null;
					mediaPlayer = new MediaPlayer();
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	Handler handler = new Handler();
	// 歌词滚动线程
	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			MusicPlayFragment.lrcView.SetIndex(LrcIndex());
			MusicPlayFragment.lrcView.invalidate();
			handler.postDelayed(runnable, 100);
		}
	};

	// 创建对象
	private List<LrcContent> lrcList = new ArrayList<LrcContent>();
	// 初始化歌词检索词
	private int index = 0;
	// 初始化歌词播放时间的变量
	private int currentTime = 0;
	// 初始化歌词播放总时间的变量
	private int countTime = 0;

	/**
	 * 歌词同步处理类
	 */
	public int LrcIndex() {
		if (mediaPlayer.isPlaying()) {
			// 获取歌曲播放到哪里的时间
			currentTime = mediaPlayer.getCurrentPosition();
			// 获取歌曲总时间长度
			countTime = mediaPlayer.getDuration();
		}
		if (currentTime < countTime) {
			for (int i = 0; i < lrcList.size(); i++) {
				if (i < lrcList.size() - 1) {
					if (currentTime < lrcList.get(i).getLrc_time() && i == 0) {
						index = i;
					}
					if (currentTime > lrcList.get(i).getLrc_time()
							&& currentTime < lrcList.get(i + 1).getLrc_time()) {
						index = i;
					}
				}
				if (i == lrcList.size() - 1
						&& currentTime > lrcList.get(i).getLrc_time()) {
					index = i;
				}
			}
		}
		return index;
	}

	private void playMusic(int id) {
		try {
			// 初始化歌词配置
			lrcProcess = new LrcProcess();
			// 读取歌词
			lrcProcess.readLRC(lists.get(id).getUrl());
			// 传回处理后的歌词文件
			lrcList = lrcProcess.getLrcContent();
			MusicPlayFragment.lrcView.setSentenceEntities(lrcList);
			// 切换带动画显示歌词
			MusicPlayFragment.lrcView.setAnimation(AnimationUtils
					.loadAnimation(MusicService.this, R.anim.alpha_z));
			// 启动线程
			handler.post(runnable);
			if (null != mediaPlayer) {
				mediaPlayer.release();
				mediaPlayer = null;
			}
			if (id > lists.size() - 1) {
				mid = lists.size() - 1;
			} else if (id < 0) {
				mid = 0;
			}
			DataMusicClass m = lists.get(mid);
			String url = m.getUrl();
			Uri uri = Uri.parse(url);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.reset();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

			mediaPlayer.setDataSource(getApplicationContext(), uri);
			mediaPlayer.prepare();

			mediaPlayer.start();
			int position = mediaPlayer.getCurrentPosition();
			int total = mediaPlayer.getDuration();
			Intent intent = new Intent("com.example.frmusic.progress");
			intent.putExtra("position", position);
			intent.putExtra("total", total);
			sendBroadcast(intent);
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					if (mp.isPlaying()) {

					}
					// 下一首
					if (MusicPlayFragment.isLoop == true) {
						mp.reset();
						Intent intent = new Intent(
								"com.example.frmusic.completion");
						sendBroadcast(intent);
						if (MusicPlayFragment.model == 1) {
							mid = mid
									+ (int) (Math.random() * lists.size() + 1);
						} else if (MusicPlayFragment.model == 2) {
							mid = mid + 1;
							if (MusicFragment.musicLsts == mid) {// 到最后一条
								mid = 0;
							}
						} else if (MusicPlayFragment.model == 3) {
							mid = mid;
						}
						playMusic(mid);
					} else {// 单曲播放
						mp.reset();
						Intent intent = new Intent(
								"com.example.frmusic.completion");
						sendBroadcast(intent);
						playMusic(mid);
					}
					sp.edit().putInt("currentMusic", mid).commit();// 保存当前播放的music
																	// id以备其他模块使用
				}
			});
			mediaPlayer.setOnErrorListener(new OnErrorListener() {

				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					if (null != mediaPlayer) {
						mediaPlayer.release();
						mediaPlayer = null;
					}
					DataMusicClass m = lists.get(mid);
					String url = m.getUrl();
					Uri uri = Uri.parse(url);
					mediaPlayer = new MediaPlayer();
					mediaPlayer.reset();
					mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
					try {
						mediaPlayer.setDataSource(getApplicationContext(), uri);
						mediaPlayer.prepare();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					mediaPlayer.start();
					return false;
				}
			});
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

}
